<template>
  <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" :title="title" width="40%" @close="close">
    <el-form ref="formRef" label-width="140px" :model="form" :rules="rules">
      <el-form-item label="定时推送时间：" prop="push_time">
        <el-time-picker v-model="form.push_time" format="HH:00" placeholder="请选择定时推送时间"
          value-format="HH:00" style="flex: 1;"/>
      </el-form-item>
      <el-form-item label="消息类型：" prop="msg_type">
        <el-select v-model="form.msg_type" placeholder="请选择消息类型" style="flex-grow: 1">
          <el-option v-for="item in weComType" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.msg_type == 'text'" label="文字消息：" prop="content">
        <el-input v-model.trim="form.content" placeholder="请输入文字消息" rows="5" type="textarea" />
      </el-form-item>
      <el-form-item v-if="form.msg_type == 'miniprogram'" label="APPID：" prop="appid">
        <el-input v-model.trim="form.appid" placeholder="请输入小程序APPID" />
      </el-form-item>
      <el-form-item v-if="form.msg_type == 'link' || form.msg_type == 'miniprogram'" label="推送标题：" prop="title">
        <el-input v-model.trim="form.title" placeholder="请输入推送标题" />
      </el-form-item>
      <el-form-item v-if="form.msg_type == 'link'" label="推送描述：" prop="desc">
        <el-input v-model.trim="form.desc" placeholder="请输入推送描述" rows="3" type="textarea" />
      </el-form-item>
      <el-form-item v-if="form.msg_type == 'link' || form.msg_type == 'miniprogram'" label="跳转链接：" prop="url">
        <el-input v-model.trim="form.url" placeholder="请输入跳转链接" rows="2" type="textarea" />
      </el-form-item>
      <el-form-item v-if="form.msg_type == 'image' ||
    form.msg_type == 'link' ||
    form.msg_type == 'miniprogram'
    " label="素材：" prop="media_id">
        <div class="file_pot">
          <el-upload ref="upload" accept="image/jpeg,image/gif,image/png" :action="action" :auto-upload="false" :class="[
    'upload-content',
    fileList.length == 0 ? 'upload_show' : 'upload_hide',
  ]" :file-list="fileList" :limit="limit" :list-type="picture" :multiple="true" :on-change="handleChange"
            :on-exceed="handleExceed" :on-preview="handlePreview" :on-remove="handleRemove">
            <template #trigger v-if="fileList.length == 0">
              <vab-icon class="avatar-uploader-icon" icon="add-line" />
            </template>
            <el-dialog v-model="dialogVisible" append-to-body title="查看大图">
              <div class="upload-image">
                <el-image :src="dialogImageUrl" />
              </div>
            </el-dialog>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { setTimePush, uploadWeCom, getWeComMedia } from '@/api/enterpriseWeChat/weCom'
export default defineComponent({
  name: 'TableTimeEdit',
  emits: ['fetch-data'],
  setup(props, { emit }) {
    const $baseMessage = inject('$baseMessage')
    const state = reactive({
      formRef: null,
      form: {
        msg_type: '',
        content: '',
        title: '',
        desc: '',
        url: '',
        media_id: '',
        appid: '',
        push_time: '',
      },
      rules: {
        msg_type: [
          { required: true, trigger: 'blur', message: '请选择消息类型' },
        ],
        push_time: [
          { required: true, trigger: 'blur', message: '请选择定时推送时间' },
        ],
        appid: [{ required: true, trigger: 'blur', message: '请输入APPID' }],
        content: [
          { required: true, trigger: 'blur', message: '请输入文字消息' },
        ],
        title: [
          { required: true, trigger: 'blur', message: '请输入推送标题' },
        ],
        desc: [
          { required: true, trigger: 'blur', message: '请输入推送描述' },
        ],
        url: [{ required: true, trigger: 'blur', message: '请输入跳转链接' }],
        media_id: [
          { required: true, trigger: 'blur', message: '请上传素材' },
        ],
      },
      title: '',
      corp_id: '',
      open_kfid: '',
      limit: 1,
      size: 1,
      picture: 'picture',
      action: '',
      fileList: [],
      weComType: [],
      dialogImageUrl: [],
      bookAllList: [],
      dialogVisible: false,
      dialogFormVisible: false,
    })
    const handlePreview = (file) => {
      state.dialogImageUrl = file.url
      state.dialogVisible = true
    }
    const handleChange = (file) => {
      if (file.size > 1048576 * state.size) {
        $baseMessage('图片不能超过1MB', 'error', 'vab-hey-error-success')
        state.fileList = []
      } else {
        const formData = new FormData()
        formData.append('corp_id', state.corp_id)
        formData.append('file', file.raw)
        uploadData(formData)
      }
    }
    const handleExceed = () => {
      $baseMessage('每次只能上传一张哦', 'error', 'vab-hey-error-success')
    }
    const handleRemove = () => {
      state.fileList = []
      state.form.media_id = ''
      $baseMessage('移除成功', 'success', 'vab-hey-message-success')
    }
    const uploadData = async (file) => {
      state.fileList.push({ url: '', name: '查看详情' })
      const { code, message, data } = await uploadWeCom(file)
      if (code == 200) {
        state.form.media_id = data.media_id
      } else {
        state.fileList = []
      }
      $baseMessage(message, 'success', 'vab-hey-message-success')
    }
    const handletHumb = async (row) => {
      const { data } = await getWeComMedia({
        corp_id: state.corp_id,
        media_id: row.media_id,
      })
      state.form.media_id = row.media_id
      state.fileList.push({
        url: data.url,
        name: '查看详情',
      })
    }
    const showEdit = (weComType, corp_id, open_kfid, row) => {
      state.weComType = weComType
      state.corp_id = corp_id
      state.open_kfid = open_kfid
      if (row) {
        state.title = '编辑定时推送消息'
        state.form = Object.assign({}, row)
        handletHumb(row)
        state.dialogFormVisible = true
      } else {
        state.title = '添加定时推送消息'
        state.dialogFormVisible = true
      }
    }
    const close = () => {
      state['formRef'].resetFields()
      state.form = {}
      state.fileList = []
      state.dialogFormVisible = false
    }
    const save = () => {
      state['formRef'].validate(async (valid) => {
        if (valid) {
          state.form.corp_id = state.corp_id
          state.form.open_kfid = state.open_kfid
          const { message } = await setTimePush(state.form)
          $baseMessage(message, 'success', 'vab-hey-message-success')
          emit('fetch-data')
          close()
        }
      })
    }
    return {
      ...toRefs(state),
      showEdit,
      close,
      save,
      handleChange,
      handlePreview,
      handleExceed,
      handleRemove,
    }
  },
})
</script>
